package com.qualityevaluationclouduser.task;

import com.qualityevaluationclouduser.entity.UserInfo;
import com.qualityevaluationclouduser.repository.UserInfoRepository;
import com.qualityevaluationclouduser.untils.AuthMDA;
import com.qualityevaluationclouduser.untils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ImagTask {

    @Value("${web.upload.path}")
    String basePath;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Scheduled(cron = "0 0 0 1/1 * ? ")
//    @Scheduled(cron = "0/30 * * * * ? ")
    public void execute() {
        List<String> fileNameList = new ArrayList<>();
        List<UserInfo> all = userInfoRepository.findAll();
        for (UserInfo userInfo : ListUtil.nvlList(all)) {
            String avatar = userInfo.getAvatar();
            if (!StringUtils.isEmpty(avatar))
                fileNameList.add(avatar);
        }
        System.out.println(fileNameList.toString());
        String[] list = new File(basePath).list();
        if (null != list) {
            for (String s : list) {
                File file = new File(basePath + "\\" + s);
                String name = file.getName();
                String avatar = AuthMDA.UPLOAD_PATH + name;
                log.info("发现文件夹中有：" + avatar);
                if (!fileNameList.contains(avatar)) {
                    log.info("该文件判定为非法，将删除：" + name);
                    FileSystemUtils.deleteRecursively(new File(basePath + name));
                }
            }
        }
    }
}
